<template>
    <div ref="editableDiv" contenteditable="true" @keydown.enter="handleEnter" @input="handleInput"
        class="markdown-editor">
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, onMounted } from 'vue';

export default defineComponent({
  name: 'MarkdownEditor',
  setup() {
    const editableDiv = ref<HTMLElement | null>(null);
    let lastText = '';

    // 处理输入事件
    const handleInput = () => {
      if (editableDiv.value) {
        lastText = editableDiv.value.innerText;
      }
    };

    // 处理回车键事件
    const handleEnter = (e: KeyboardEvent) => {
      if (!editableDiv.value) return;

      const selection = window.getSelection();
      if (!selection || selection.rangeCount === 0) return;

      const range = selection.getRangeAt(0);
      const lineText = getCurrentLineText(range);

      // 阻止默认回车行为，我们将自己处理
      e.preventDefault();

      // 检查特殊字符并格式化
      if (lineText.startsWith('# ')) {
        formatHeading(lineText.substring(2), 1);
      } else if (lineText.startsWith('## ')) {
        formatHeading(lineText.substring(3), 2);
      } else if (lineText.startsWith('### ')) {
        formatHeading(lineText.substring(4), 3);
      } else {
        // 普通回车行为
        document.execCommand('insertLineBreak');
      }
    };

    // 获取当前行的文本
    const getCurrentLineText = (range: Range): string => {
      const container = range.startContainer as Node;
      const text = container.textContent || '';
      const startOffset = range.startOffset;
      
      // 找到行首
      let lineStart = text.lastIndexOf('\n', startOffset - 1) + 1;
      // 找到行尾
      let lineEnd = text.indexOf('\n', startOffset);
      if (lineEnd === -1) lineEnd = text.length;
      
      return text.substring(lineStart, lineEnd);
    };

    // 格式化标题
    const formatHeading = (text: string, level: number) => {
      if (!editableDiv.value) return;

      const selection = window.getSelection();
      if (!selection || selection.rangeCount === 0) return;

      const range = selection.getRangeAt(0);
      const container = range.startContainer as Node;
      const textNode = container.parentNode?.parentNode === editableDiv.value 
        ? container 
        : container.parentNode;

      if (!textNode || !textNode.parentNode) return;

      // 创建新的标题元素
      const heading = document.createElement(`h${level}`);
      heading.textContent = text;
      heading.style.textAlign = 'center'; // 居中显示

      // 替换当前行
      const lineRange = document.createRange();
      lineRange.selectNodeContents(textNode);
      lineRange.deleteContents();
      lineRange.insertNode(heading);

      // 添加新段落
      const newParagraph = document.createElement('p');
      newParagraph.innerHTML = '<br>';
      editableDiv.value.appendChild(newParagraph);

      // 将光标移动到新段落
      const newRange = document.createRange();
      newRange.setStart(newParagraph, 0);
      newRange.setEnd(newParagraph, 0);
      selection.removeAllRanges();
      selection.addRange(newRange);
    };

    onMounted(() => {
      if (editableDiv.value) {
        // 初始化时添加一个空段落
        const p = document.createElement('p');
        p.innerHTML = '<br>';
        editableDiv.value.appendChild(p);
      }
    });

    return {
      editableDiv,
      handleEnter,
      handleInput
    };
  }
});
</script>

<style scoped>
.markdown-editor {
  width: 100vw;
  height: 100vh;
  border: 1px solid #ccc;
  padding: 10px;
  border-radius: 4px;
  outline: none;
}

.markdown-editor:focus {
  border-color: #409eff;
}

.markdown-editor h1, 
.markdown-editor h2, 
.markdown-editor h3 {
  text-align: center;
  margin: 10px 0;
}

.markdown-editor h1 {
  font-size: 2em;
}

.markdown-editor h2 {
  font-size: 1.5em;
}

.markdown-editor h3 {
  font-size: 1.17em;
}
</style>